<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import {
    useGetAmountStatistics,
    useGetBuyerOrderPage,
    useGetContractDetail,
    useGetDeliveryOrderPage,
} from '@fl/api/supplier'
import { ReasonDialog, SearchForm, SearchTable } from '@fl/components'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import BuyerOrder from './buyer-order.vue'
import {
    BUYER_ORDER_QUERY_TYPE,
    CONTRACT_STATUS,
    DELIVERY_ORDER_QUERY_TYPE,
    DELIVERY_ORDER_STATE_OPTIONS,
    REQUEST_STATUS,
    REQUEST_STATUS_OPTIONS,
} from './constant'
import DeliveryOrder from './delivery-order.vue'

defineOptions({
    name: window.location.href.includes('supplier-pages')
        ? '/supplier-pages/order-management/contract-detail'
        : '/purchase-pages/purchase-order-management/contract-detail',
})

const router = useRouter()
const route = useRoute()

const activeName = ref<string>('applyingAmount')
const tabList = computed(() => [
    {
        label: '请款申请',
        name: 'applyingAmount',
    },
    {
        label: isSupplier.value ? '已发货' : '已收货',
        name: isSupplier.value ? 'shippedAmount' : 'receivedAmount',
    },
    {
        label: '已验收',
        name: 'acceptedAmount',
    },
    {
        label: isSupplier.value ? '已收款' : '已付款',
        name: isSupplier.value ? 'payReceived' : 'paidAmount',
    },
])

const showDeliveryOrder = ref<boolean>(false)
const deliveryOrderId = ref<string>('')
const showBuyerOrder = ref<boolean>(false)
const buyerOrderId = ref<string>('')
const buyerOrderBusinessType = ref<'addRequest' | 'payDetail' | 'requestDetail' | 'resubmit' | undefined>(undefined)
const showReason = ref<boolean>(false)
const reason = ref<string>('')
const reasonDialogTitle = ref<string>('')

const initialState = {} as any
const state = ref(cloneDeep(initialState))

const isSupplier = computed(() => route.path.includes('supplier-pages'))
const isBuyerOrderActive = computed(() => ['applyingAmount', 'paidAmount', 'payReceived'].includes(activeName.value))
const isPaidAmountActive = computed(() => activeName.value === 'paidAmount')
const getAmountStatisticsParams = computed(() => ({
    contractId: route.query.id as string,
    manufacturerType: isSupplier.value ? 1 : 2,
}))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const buyerOrderQueryType = computed(() => ({
    applyingAmount: BUYER_ORDER_QUERY_TYPE.APPLY_ORDER,
    paidAmount: BUYER_ORDER_QUERY_TYPE.RECEIVE_ORDER,
    payReceived: BUYER_ORDER_QUERY_TYPE.RECEIVE_ORDER,
}[activeName.value]))
const deliveryOrderQueryType = computed(() => ({
    acceptedAmount: DELIVERY_ORDER_QUERY_TYPE.ACCEPTED,
    receivedAmount: DELIVERY_ORDER_QUERY_TYPE.RECEIVED,
    shippedAmount: DELIVERY_ORDER_QUERY_TYPE.DELIVERED,
}[activeName.value]))
const getBuyerOrderPageParams = computed(() => ({
    contractId: isBuyerOrderActive.value ? (route.query.id as string) : '',
    manufacturerType: isSupplier.value ? 1 : 2,
    page: tablePage.currentPage,
    queryType: buyerOrderQueryType.value,
    size: tablePage.pageSize,
}))
const getDeliveryOrderPageParams = computed(() => ({
    contractId: isBuyerOrderActive.value ? '' : (route.query.id as string),
    manufacturerType: isSupplier.value ? 1 : 2,
    page: tablePage.currentPage,
    queryType: deliveryOrderQueryType.value,
    size: tablePage.pageSize,
}))

const { data: contractDetailData, isLoading: isGetContractDetailLoading } = useGetContractDetail(route.query.id as string)
const { data: amountStatisticsData, isLoading: isGetAmountStatisticsLoading } = useGetAmountStatistics(getAmountStatisticsParams)
const { data: buyerOrderPageData, isLoading: isGetBuyerOrderPageLoading, total: buyerOrderTotal } = useGetBuyerOrderPage(getBuyerOrderPageParams)
const {
    data: deliveryOrderPageData,
    isLoading: isGetDeliveryOrderPageLoading,
    total: deliveryOrderTotal,
} = useGetDeliveryOrderPage(getDeliveryOrderPageParams)

// #region Form
const isFormLoading = computed(() => isGetContractDetailLoading.value || isGetAmountStatisticsLoading.value)

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 8,
        },
        label: '合同名称',
        prop: 'agreementName',
        valueType: 'text',
    },
    {
        colProps: {
            span: 8,
        },
        label: '甲方',
        prop: 'partyA',
        valueType: 'text',
    },
    // {
    //     colProps: {
    //         span: 8,
    //     },
    //     label: '协议类目',
    //     prop: 'categoryName',
    //     valueType: 'text',
    // },
    {
        colProps: {
            span: 8,
        },
        label: '合同总金额',
        prop: 'contractPrice',
        renderField: (value: any) => `${value || 0}元`,
    },
    {
        colProps: {
            span: 8,
        },
        label: isSupplier.value ? '已开票总金额' : '已收票总金额',
        prop: isSupplier.value ? 'totalAmountInvoiced' : 'totalInvoiceReceived',
        renderField: (value: any) => `${value || 0}元`,
    },
    {
        colProps: {
            span: 8,
        },
        hideInForm: computed(() => Number.isNaN(state.value.contractPrice) || !state.value.contractPrice),
        label: isSupplier.value ? '剩余未收总金额' : '剩余未付总金额',
        prop: isSupplier.value ? 'remainingAmountDue' : 'remainingUnpaid',
        renderField: (value: any) => `${value || 0}元`,
    },
]
// #endregion

// #region Table
const isTableLoading = computed(() => isBuyerOrderActive.value ? isGetBuyerOrderPageLoading.value : isGetDeliveryOrderPageLoading.value)
const tableData = computed(() => isBuyerOrderActive.value ? buyerOrderPageData.value : deliveryOrderPageData.value)

const gridOptions = computed<VxeGridProps>(() => ({
    columns: isBuyerOrderActive.value
        ? isPaidAmountActive.value
            ? [
                    { field: 'requestNumber', title: '申请编号', width: 170 },
                    { field: 'requestTime', title: '申请时间', width: 170 },
                    { field: 'requestAmount', title: '申请金额（元）' },
                    { field: 'invoiceAmount', title: '开票金额（元）' },
                    { field: 'actualPaidAmount', title: '实付金额（元）' },
                    { field: 'actualInvoiceAmount', title: '收票金额（元）' },
                    { field: 'requestStatus', formatter: formatRequestStatus, title: '状态' },
                    { field: 'applicant', title: '申请人' },
                    { slots: { default: 'operation' }, title: '操作', width: 300 },
                ]
            : [
                    { field: 'requestNumber', title: '申请编号', width: 170 },
                    { field: 'requestTime', title: '申请时间', width: 170 },
                    { field: 'requestAmount', title: '申请金额（元）' },
                    { field: 'invoiceAmount', title: '开票金额（元）' },
                    { field: 'requestStatus', formatter: formatRequestStatus, title: '状态' },
                    { field: 'applicant', title: '申请人' },
                    { slots: { default: 'operation' }, title: '操作', width: 300 },
                ]
        : [
                { field: 'deliveryNoteNo', title: '发货单号', width: 200 },
                { field: 'estimatedShippingDate', title: '发货时间', width: 170 },
                { field: 'logisticsCompany', title: '物流公司' },
                { field: 'trackingNumber', title: '物流单号' },
                { field: 'quantity', title: '发货数量' },
                { field: 'acceptedQuantity', title: '验收数量' },
                { field: 'totalValue', title: '货值（元）' },
                { field: 'deliveryNoteState', formatter: formatDeliveryNoteState, title: '状态' },
                { slots: { default: 'operation' }, title: '操作', width: 200 },
            ],
}))

function formatRequestStatus({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: REQUEST_STATUS_OPTIONS })
}
function formatDeliveryNoteState({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: DELIVERY_ORDER_STATE_OPTIONS })
}

watchEffect(() => {
    tablePage.total = isBuyerOrderActive.value ? buyerOrderTotal.value : deliveryOrderTotal.value
})
// #endregion

// #region UI Listener
function onCheckDetailBtnClick(row: any) {
    if (isBuyerOrderActive.value) {
        buyerOrderId.value = row.id
        buyerOrderBusinessType.value = isSupplier.value ? 'requestDetail' : 'payDetail'
        showBuyerOrder.value = true
    }
    else {
        deliveryOrderId.value = row.id
        showDeliveryOrder.value = true
    }
}

function onResubmitBtnClick(row: any) {
    buyerOrderId.value = row.id
    buyerOrderBusinessType.value = 'resubmit'
    showBuyerOrder.value = true
}

function onCheckReasonBtnClick(row: any) {
    const requestStatusToReasonFieldMap = {
        [REQUEST_STATUS.REJECTED]: 'rejectReason',
        [REQUEST_STATUS.RETURNED]: 'returnReason',
    }
    reason.value = row[requestStatusToReasonFieldMap[row.requestStatus]]
    const reasonDialogTitleMap = {
        [REQUEST_STATUS.REJECTED]: '驳回请款',
        [REQUEST_STATUS.RETURNED]: '退回付款',
    }
    reasonDialogTitle.value = reasonDialogTitleMap[row.requestStatus]
    showReason.value = true
}

function onBackBtnClick() {
    router.back()
}

function onApplyReceivingBtnClick() {
    buyerOrderId.value = ''
    buyerOrderBusinessType.value = 'addRequest'
    showBuyerOrder.value = true
}
// #endregion

watchEffect(() => {
    state.value = cloneDeep(contractDetailData.value)
})

watch(activeName, () => {
    tablePage.currentPage = 1
})
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <SearchForm v-else
                    v-model="state"
                    :columns="columns"
                    :row-props="{ gutter: 40 }"
                    :has-footer="false"
                    :label-width="150"
        />

        <div class="flex justify-between">
            <el-tabs v-model="activeName"
                     class="demo-tabs"
            >
                <el-tab-pane v-for="item in tabList"
                             :key="item.name"
                             :label="item.label"
                             :name="item.name"
                >
                    <template #label>
                        <div class="px-16 font-normal text-center w-200">
                            {{ `${item.label}(${amountStatisticsData?.[item.name] || 0}元)` }}
                        </div>
                    </template>
                </el-tab-pane>
            </el-tabs>

            <el-button v-if="isSupplier && state?.contractStatus !== CONTRACT_STATUS.COMPLETED"
                       type="primary"
                       class="mt-4 float-right"
                       @click="onApplyReceivingBtnClick"
            >
                请款申请
            </el-button>
        </div>

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="tableData"
        >
            <template #operation="{ row }">
                <el-button text
                           type="primary"
                           class="!p-4"
                           @click="onCheckDetailBtnClick(row)"
                >
                    查看
                </el-button>

                <el-button v-if="isSupplier && [REQUEST_STATUS.REJECTED, REQUEST_STATUS.RETURNED].includes(row.requestStatus)"
                           text
                           type="primary"
                           class="!p-4"
                           @click="onResubmitBtnClick(row)"
                >
                    重新发起
                </el-button>

                <el-button v-if="[REQUEST_STATUS.REJECTED, REQUEST_STATUS.RETURNED].includes(row.requestStatus)"
                           text
                           type="primary"
                           class="!p-4"
                           @click="onCheckReasonBtnClick(row)"
                >
                    查看原因
                </el-button>
            </template>
        </SearchTable>
    </el-card>

    <div class="mt-20 flex justify-center">
        <el-button @click="onBackBtnClick">
            返回
        </el-button>
    </div>

    <BuyerOrder :key="buyerOrderId"
                v-model:id="buyerOrderId"
                v-model:visible="showBuyerOrder"
                :contract-detail-data="contractDetailData"
                :business-type="buyerOrderBusinessType"
    />

    <DeliveryOrder :key="deliveryOrderId"
                   v-model:id="deliveryOrderId"
                   v-model:visible="showDeliveryOrder"
    />

    <ReasonDialog v-model:visible="showReason"
                  :title="reasonDialogTitle"
                  mode="check"
                  :reason="reason"
    />
</template>

<style lang="scss" scoped>
:deep(.el-tabs__nav-wrap::after) {
    height: 0;
}
</style>
